/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lambkit.module.upms.service;

import com.lambkit.core.Attr;
import com.lambkit.core.Lambkit;
import com.lambkit.db.DbPool;
import com.lambkit.db.AbstractDaoService;
import com.lambkit.db.IRowDao;
import com.lambkit.db.sql.Example;
import com.lambkit.module.upms.Upms;
import com.lambkit.module.upms.UpmsConfig;
import com.lambkit.module.upms.row.UpmsUser;
import com.lambkit.module.upms.sql.UpmsUserSQL;

import java.util.List;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date ${date}
 * @version 1.0
 * @since 1.0
 */

public class UpmsUserService extends AbstractDaoService<UpmsUser> {
	public static UpmsUserService of() {
		return Lambkit.get(UpmsUserService.class);
	}
	public IRowDao<UpmsUser> dao() {
		String dbPoolName = Lambkit.config(UpmsConfig.class).getDbPoolName();
		return DbPool.use(dbPoolName).dao(UpmsUser.class);
	}

	public IRowDao<UpmsUser> dao(String dbPoolName) {
		return DbPool.use(dbPoolName).dao(UpmsUser.class);
	}

    public UpmsUser findByPrimaryKey(Long upmsUserId) {
		Example example = UpmsUserSQL.of().andUserIdEqualTo(upmsUserId).example();
		return dao().findFirst(example);
    }

	public UpmsUser getUser(String username) {
		Example upmsUserExample = UpmsUserSQL.of().andUsernameEqualTo(username).example();
		return dao().findFirst(upmsUserExample);
	}

	public UpmsUser createUser(UpmsUser upmsUser) {
		Example upmsUserExample = UpmsUserSQL.of()
				.andUsernameEqualTo(upmsUser.getUsername()).example().setSelectSql(" count(*) ") ;
		Long count = dao().count(upmsUserExample);
		if (count!=null && count > 0) {
			return null;
		}
		dao().save(upmsUser);
		return upmsUser;
	}

	public List<UpmsUser> findUserByOrgId(Long orgId) {
		Attr data = Attr.by("orgId", orgId);
		return Upms.getApiService().find("upms.selectUpmsUserByOrgId", UpmsUser.class, data);
	}
}
